<script setup lang="ts">
import { ref, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { userApi } from '@/api/customer';

const router = useRouter();
const loading = ref(false);
const agreeTerms = ref(false);

const registerForm = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  phone: '',
  email: ''
});

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度应为3-20个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度应为6-20个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule: any, value: string, callback: Function) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入的密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { 
      type: 'email', 
      message: '请输入正确的邮箱地址', 
      trigger: 'blur' 
    },
    {
      validator: (rule: any, value: string, callback: Function) => {
        if (value && !/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/.test(value)) {
          callback(new Error('邮箱格式不正确'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
};

const registerFormRef = ref();

// 处理注册
const handleRegister = async () => {
  if (!registerFormRef.value) return;
  
  if (!agreeTerms.value) {
    ElMessage.warning('请先阅读并同意用户协议');
    return;
  }
  
  // 检查必填字段
  if (!registerForm.username || !registerForm.password || !registerForm.confirmPassword) {
    ElMessage.warning('请填写完整必填信息');
    return;
  }
  
  await registerFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        loading.value = true;
        const response = await userApi.register({
          username: registerForm.username,
          password: registerForm.password,
          phone: registerForm.phone || '',
          email: registerForm.email || ''
        });
        
        // 处理特定的状态码
        if (response.status === 1001) {
          ElMessage.error('用户名已存在，请选择其他用户名');
          return;
        }
        
        ElMessage.success('注册成功，请登录');
        // 延迟跳转，让用户看到成功消息
        setTimeout(() => {
          router.push('/customer/login');
        }, 1500);
      } catch (error: any) {
        console.error('注册失败:', error);
        // 根据错误响应显示具体错误信息
        if (error.response?.data?.status === 1001) {
          ElMessage.error('用户名已存在，请选择其他用户名');
        } else {
          ElMessage.error(error.response?.data?.message || error.message || '注册失败，请稍后再试');
        }
      } finally {
        loading.value = false;
      }
    }
  });
};

// 跳转到登录页面
const goToLogin = () => {
  router.push('/customer/login');
};

// 跳转到首页
const goToHome = () => {
  router.push('/customer');
};

// 打开用户协议
const openTerms = () => {
  // 这里可以打开用户协议对话框
  ElMessage.info('用户协议功能开发中');
};
</script>

<template>
  <div class="register-container">
    <div class="register-box">
      <div class="register-header">
        <img src="/logo.png" alt="饱了么" class="logo" @click="goToHome" />
        <h2 class="title">饱了么 - 用户注册</h2>
      </div>
      
      <el-form 
        ref="registerFormRef"
        :model="registerForm"
        :rules="rules"
        label-position="top"
        class="register-form"
      >
        <el-form-item label="用户名" prop="username">
          <el-input 
            v-model="registerForm.username"
            placeholder="请输入用户名"
            prefix-icon="el-icon-user"
          />
        </el-form-item>
        
        <el-form-item label="密码" prop="password">
          <el-input 
            v-model="registerForm.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="el-icon-lock"
            show-password
          />
        </el-form-item>
        
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input 
            v-model="registerForm.confirmPassword"
            type="password"
            placeholder="请再次输入密码"
            prefix-icon="el-icon-lock"
            show-password
          />
        </el-form-item>
        
        <el-form-item label="手机号码" prop="phone">
          <el-input 
            v-model="registerForm.phone"
            placeholder="请输入手机号码"
            prefix-icon="el-icon-mobile-phone"
          />
        </el-form-item>
        
        <el-form-item label="电子邮箱" prop="email">
          <el-input 
            v-model="registerForm.email"
            placeholder="请输入电子邮箱"
            prefix-icon="el-icon-message"
          />
        </el-form-item>
        
        <div class="terms-checkbox">
          <el-checkbox v-model="agreeTerms">
            我已阅读并同意 <el-link type="primary" @click.stop="openTerms">《用户协议》</el-link>
          </el-checkbox>
        </div>
        
        <el-form-item>
          <el-button 
            type="primary" 
            :loading="loading" 
            class="register-button"
            @click="handleRegister"
          >
            注册
          </el-button>
        </el-form-item>
      </el-form>
      
      <div class="login-link">
        已有账号? <el-link type="primary" @click="goToLogin">立即登录</el-link>
      </div>
      
      <div class="back-to-home">
        <el-link type="info" @click="goToHome">
          <i class="el-icon-arrow-left"></i> 返回首页
        </el-link>
      </div>
    </div>
  </div>
</template>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #ffe082 0%, #ffd54f 100%);
}

.register-box {
  width: 450px;
  padding: 30px;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  margin: 40px 0;
}

.register-header {
  text-align: center;
  margin-bottom: 25px;
}

.logo {
  width: 60px;
  height: 60px;
  margin-bottom: 15px;
  cursor: pointer;
}

.title {
  font-size: 24px;
  color: #8b4513;
  margin: 0;
}

.register-form {
  margin-bottom: 20px;
}

.terms-checkbox {
  margin: 20px 0;
}

.register-button {
  width: 100%;
  padding: 12px;
  font-size: 16px;
}

.login-link {
  text-align: center;
  margin-top: 20px;
  color: #666;
}

.back-to-home {
  margin-top: 20px;
  text-align: center;
}
</style>
